{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f36d938c",
   "metadata": {},
   "source": [
    "# Model caches\n",
    "\n",
    "This notebook covers how to cache results of individual LLM calls using different caches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "10ad9224",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-12T02:05:57.319706Z",
     "start_time": "2024-04-12T02:05:57.303868Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain.globals import set_llm_cache\n",
    "from langchain_openai import OpenAI\n",
    "\n",
    "# To make the caching really obvious, lets use a slower model.\n",
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", n=2, best_of=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b50f0598",
   "metadata": {
    "tags": []
   },
   "source": [
    "## `In Memory` Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "426ff912",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.cache import InMemoryCache\n",
    "\n",
    "set_llm_cache(InMemoryCache())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "64005d1f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 52.2 ms, sys: 15.2 ms, total: 67.4 ms\n",
      "Wall time: 1.19 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy couldn't the bicycle stand up by itself? Because it was...two tired!\""
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c8a1cb2b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 191 µs, sys: 11 µs, total: 202 µs\n",
      "Wall time: 205 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy couldn't the bicycle stand up by itself? Because it was...two tired!\""
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bf59c12",
   "metadata": {
    "tags": []
   },
   "source": [
    "## `SQLite` Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aefd9d2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm .langchain.db"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5f036236",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can do the same thing with a SQLite cache\n",
    "from langchain_community.cache import SQLiteCache\n",
    "\n",
    "set_llm_cache(SQLiteCache(database_path=\".langchain.db\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fa18e3af",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 33.2 ms, sys: 18.1 ms, total: 51.2 ms\n",
      "Wall time: 667 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5bf2f6fd",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.86 ms, sys: 1.97 ms, total: 6.83 ms\n",
      "Wall time: 5.79 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e71273ab",
   "metadata": {},
   "source": [
    "## `Upstash Redis` Cache"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f10dabef",
   "metadata": {},
   "source": [
    "### Standard Cache\n",
    "Use [Upstash Redis](https://upstash.com) to cache prompts and responses with a serverless HTTP API."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f3920f25",
   "metadata": {},
   "outputs": [],
   "source": [
    "import langchain\n",
    "from langchain_community.cache import UpstashRedisCache\n",
    "from upstash_redis import Redis\n",
    "\n",
    "URL = \"<UPSTASH_REDIS_REST_URL>\"\n",
    "TOKEN = \"<UPSTASH_REDIS_REST_TOKEN>\"\n",
    "\n",
    "langchain.llm_cache = UpstashRedisCache(redis_=Redis(url=URL, token=TOKEN))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "3bf7d959",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 7.56 ms, sys: 2.98 ms, total: 10.5 ms\n",
      "Wall time: 1.14 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "00fc3a34",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2.78 ms, sys: 1.95 ms, total: 4.73 ms\n",
      "Wall time: 82.9 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "278ad7ae",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `Redis` Cache"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5c9a4d5",
   "metadata": {},
   "source": [
    "### Standard Cache\n",
    "Use [Redis](/docs/integrations/providers/redis) to cache prompts and responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "39f6eb0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can do the same thing with a Redis cache\n",
    "# (make sure your local Redis instance is running first before running this example)\n",
    "from langchain_community.cache import RedisCache\n",
    "from redis import Redis\n",
    "\n",
    "set_llm_cache(RedisCache(redis_=Redis()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28920749",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 6.88 ms, sys: 8.75 ms, total: 15.6 ms\n",
      "Wall time: 1.04 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "94bf9415",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.59 ms, sys: 610 µs, total: 2.2 ms\n",
      "Wall time: 5.58 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82be23f6",
   "metadata": {},
   "source": [
    "### Semantic Cache\n",
    "Use [Redis](/docs/integrations/providers/redis) to cache prompts and responses and evaluate hits based on semantic similarity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "64df3099",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.cache import RedisSemanticCache\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "set_llm_cache(\n",
    "    RedisSemanticCache(redis_url=\"redis://localhost:6379\", embedding=OpenAIEmbeddings())\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8e91d3ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 351 ms, sys: 156 ms, total: 507 ms\n",
      "Wall time: 3.37 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "df856948",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 6.25 ms, sys: 2.72 ms, total: 8.97 ms\n",
      "Wall time: 262 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time, while not a direct hit, the question is semantically similar to the original question,\n",
    "# so it uses the cached result!\n",
    "llm(\"Tell me one joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "684eab55",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `GPTCache`\n",
    "\n",
    "We can use [GPTCache](https://github.com/zilliztech/GPTCache) for exact match caching OR to cache results based on semantic similarity\n",
    "\n",
    "Let's first start with an example of exact match"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "14a82124",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "\n",
    "from gptcache import Cache\n",
    "from gptcache.manager.factory import manager_factory\n",
    "from gptcache.processor.pre import get_prompt\n",
    "from langchain_community.cache import GPTCache\n",
    "\n",
    "\n",
    "def get_hashed_name(name):\n",
    "    return hashlib.sha256(name.encode()).hexdigest()\n",
    "\n",
    "\n",
    "def init_gptcache(cache_obj: Cache, llm: str):\n",
    "    hashed_llm = get_hashed_name(llm)\n",
    "    cache_obj.init(\n",
    "        pre_embedding_func=get_prompt,\n",
    "        data_manager=manager_factory(manager=\"map\", data_dir=f\"map_cache_{hashed_llm}\"),\n",
    "    )\n",
    "\n",
    "\n",
    "set_llm_cache(GPTCache(init_gptcache))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e4ecfd1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 21.5 ms, sys: 21.3 ms, total: 42.8 ms\n",
      "Wall time: 6.2 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c98bbe3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 571 µs, sys: 43 µs, total: 614 µs\n",
      "Wall time: 635 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "502b6076",
   "metadata": {},
   "source": [
    "Let's now show an example of similarity caching"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b3c663bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "\n",
    "from gptcache import Cache\n",
    "from gptcache.adapter.api import init_similar_cache\n",
    "from langchain_community.cache import GPTCache\n",
    "\n",
    "\n",
    "def get_hashed_name(name):\n",
    "    return hashlib.sha256(name.encode()).hexdigest()\n",
    "\n",
    "\n",
    "def init_gptcache(cache_obj: Cache, llm: str):\n",
    "    hashed_llm = get_hashed_name(llm)\n",
    "    init_similar_cache(cache_obj=cache_obj, data_dir=f\"similar_cache_{hashed_llm}\")\n",
    "\n",
    "\n",
    "set_llm_cache(GPTCache(init_gptcache))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8c273ced",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.42 s, sys: 279 ms, total: 1.7 s\n",
      "Wall time: 8.44 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "93e21a5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 866 ms, sys: 20 ms, total: 886 ms\n",
      "Wall time: 226 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# This is an exact match, so it finds it in the cache\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c4bb024b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 853 ms, sys: 14.8 ms, total: 868 ms\n",
      "Wall time: 224 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# This is not an exact match, but semantically within distance so it hits!\n",
    "llm(\"Tell me joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b2b2777",
   "metadata": {},
   "source": [
    "## `MongoDB Atlas` Cache\n",
    "\n",
    "[MongoDB Atlas](https://www.mongodb.com/docs/atlas/) is a fully-managed cloud database available in AWS, Azure, and GCP. It has native support for \n",
    "Vector Search on the MongoDB document data.\n",
    "Use [MongoDB Atlas Vector Search](/docs/integrations/providers/mongodb_atlas) to semantically cache prompts and responses."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecdc2a0a",
   "metadata": {},
   "source": [
    "### `MongoDBCache`\n",
    "An abstraction to store a simple cache in MongoDB. This does not use Semantic Caching, nor does it require an index to be made on the collection before generation.\n",
    "\n",
    "To import this cache:\n",
    "\n",
    "```python\n",
    "from langchain_mongodb.cache import MongoDBCache\n",
    "```\n",
    "\n",
    "\n",
    "To use this cache with your LLMs:\n",
    "```python\n",
    "from langchain_core.globals import set_llm_cache\n",
    "\n",
    "# use any embedding provider...\n",
    "from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n",
    "\n",
    "mongodb_atlas_uri = \"<YOUR_CONNECTION_STRING>\"\n",
    "COLLECTION_NAME=\"<YOUR_CACHE_COLLECTION_NAME>\"\n",
    "DATABASE_NAME=\"<YOUR_DATABASE_NAME>\"\n",
    "\n",
    "set_llm_cache(MongoDBCache(\n",
    "    connection_string=mongodb_atlas_uri,\n",
    "    collection_name=COLLECTION_NAME,\n",
    "    database_name=DATABASE_NAME,\n",
    "))\n",
    "```\n",
    "\n",
    "\n",
    "### `MongoDBAtlasSemanticCache`\n",
    "Semantic caching allows users to retrieve cached prompts based on semantic similarity between the user input and previously cached results. Under the hood it blends MongoDBAtlas as both a cache and a vectorstore.\n",
    "The MongoDBAtlasSemanticCache inherits from `MongoDBAtlasVectorSearch` and needs an Atlas Vector Search Index defined to work. Please look at the [usage example](/docs/integrations/vectorstores/mongodb_atlas) on how to set up the index.\n",
    "\n",
    "To import this cache:\n",
    "```python\n",
    "from langchain_mongodb.cache import MongoDBAtlasSemanticCache\n",
    "```\n",
    "\n",
    "To use this cache with your LLMs:\n",
    "```python\n",
    "from langchain_core.globals import set_llm_cache\n",
    "\n",
    "# use any embedding provider...\n",
    "from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n",
    "\n",
    "mongodb_atlas_uri = \"<YOUR_CONNECTION_STRING>\"\n",
    "COLLECTION_NAME=\"<YOUR_CACHE_COLLECTION_NAME>\"\n",
    "DATABASE_NAME=\"<YOUR_DATABASE_NAME>\"\n",
    "\n",
    "set_llm_cache(MongoDBAtlasSemanticCache(\n",
    "    embedding=FakeEmbeddings(),\n",
    "    connection_string=mongodb_atlas_uri,\n",
    "    collection_name=COLLECTION_NAME,\n",
    "    database_name=DATABASE_NAME,\n",
    "))\n",
    "```\n",
    "\n",
    "To find more resources about using MongoDBSemanticCache visit [here](https://www.mongodb.com/blog/post/introducing-semantic-caching-dedicated-mongodb-lang-chain-package-gen-ai-apps)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "726fe754",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `Momento` Cache\n",
    "Use [Momento](/docs/integrations/providers/momento) to cache prompts and responses.\n",
    "\n",
    "Requires momento to use, uncomment below to install:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8949f29",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet  momento"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56ea6a08",
   "metadata": {},
   "source": [
    "You'll need to get a Momento auth token to use this class. This can either be passed in to a momento.CacheClient if you'd like to instantiate that directly, as a named parameter `auth_token` to `MomentoChatMessageHistory.from_client_params`, or can just be set as an environment variable `MOMENTO_AUTH_TOKEN`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2005f03a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import timedelta\n",
    "\n",
    "from langchain_community.cache import MomentoCache\n",
    "\n",
    "cache_name = \"langchain\"\n",
    "ttl = timedelta(days=1)\n",
    "set_llm_cache(MomentoCache.from_client_params(cache_name, ttl))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c6a6c238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 40.7 ms, sys: 16.5 ms, total: 57.2 ms\n",
      "Wall time: 1.73 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b8f78f9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 3.16 ms, sys: 2.98 ms, total: 6.14 ms\n",
      "Wall time: 57.9 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "# When run in the same region as the cache, latencies are single digit ms\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "934943dc",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `SQLAlchemy` Cache\n",
    "\n",
    "You can use `SQLAlchemyCache` to cache with any SQL database supported by `SQLAlchemy`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acccff40",
   "metadata": {},
   "outputs": [],
   "source": [
    "# from langchain.cache import SQLAlchemyCache\n",
    "# from sqlalchemy import create_engine\n",
    "\n",
    "# engine = create_engine(\"postgresql://postgres:postgres@localhost:5432/postgres\")\n",
    "# set_llm_cache(SQLAlchemyCache(engine))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0959d640",
   "metadata": {},
   "source": [
    "### Custom SQLAlchemy Schemas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac967b39",
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can define your own declarative SQLAlchemyCache child class to customize the schema used for caching. For example, to support high-speed fulltext prompt indexing with Postgres, use:\n",
    "\n",
    "from langchain_community.cache import SQLAlchemyCache\n",
    "from sqlalchemy import Column, Computed, Index, Integer, Sequence, String, create_engine\n",
    "from sqlalchemy.ext.declarative import declarative_base\n",
    "from sqlalchemy_utils import TSVectorType\n",
    "\n",
    "Base = declarative_base()\n",
    "\n",
    "\n",
    "class FulltextLLMCache(Base):  # type: ignore\n",
    "    \"\"\"Postgres table for fulltext-indexed LLM Cache\"\"\"\n",
    "\n",
    "    __tablename__ = \"llm_cache_fulltext\"\n",
    "    id = Column(Integer, Sequence(\"cache_id\"), primary_key=True)\n",
    "    prompt = Column(String, nullable=False)\n",
    "    llm = Column(String, nullable=False)\n",
    "    idx = Column(Integer)\n",
    "    response = Column(String)\n",
    "    prompt_tsv = Column(\n",
    "        TSVectorType(),\n",
    "        Computed(\"to_tsvector('english', llm || ' ' || prompt)\", persisted=True),\n",
    "    )\n",
    "    __table_args__ = (\n",
    "        Index(\"idx_fulltext_prompt_tsv\", prompt_tsv, postgresql_using=\"gin\"),\n",
    "    )\n",
    "\n",
    "\n",
    "engine = create_engine(\"postgresql://postgres:postgres@localhost:5432/postgres\")\n",
    "set_llm_cache(SQLAlchemyCache(engine, FulltextLLMCache))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eeba7d60",
   "metadata": {},
   "source": [
    "## `Cassandra` caches\n",
    "\n",
    "> [Apache Cassandra®](https://cassandra.apache.org/) is a NoSQL, row-oriented, highly scalable and highly available database. Starting with version 5.0, the database ships with [vector search capabilities](https://cassandra.apache.org/doc/trunk/cassandra/vector-search/overview.html).\n",
    "\n",
    "You can use Cassandra for caching LLM responses, choosing from the exact-match `CassandraCache` or the (vector-similarity-based) `CassandraSemanticCache`.\n",
    "\n",
    "Let's see both in action. The next cells guide you through the (little) required setup, and the following cells showcase the two available cache classes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6cf6acb4-1bc4-4c4b-9325-2420c17e5e2b",
   "metadata": {},
   "source": [
    "### Required dependency"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe842b0d-fd3d-47dd-bc6a-975997c9707f",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet \"cassio>=0.1.4\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4a6725d",
   "metadata": {},
   "source": [
    "### Connect to the DB\n",
    "\n",
    "The Cassandra caches shown in this page can be used with Cassandra as well as other derived databases, such as Astra DB, which use the CQL (Cassandra Query Language) protocol.\n",
    "\n",
    "> DataStax [Astra DB](https://docs.datastax.com/en/astra-serverless/docs/vector-search/quickstart.html) is a managed serverless database built on Cassandra, offering the same interface and strengths.\n",
    "\n",
    "Depending on whether you connect to a Cassandra cluster or to Astra DB through CQL, you will provide different parameters when instantiating the cache (through initialization of a CassIO connection)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15735abe-2567-43ce-aa91-f253b33b5a88",
   "metadata": {},
   "source": [
    "#### Connecting to a Cassandra cluster\n",
    "\n",
    "You first need to create a `cassandra.cluster.Session` object, as described in the [Cassandra driver documentation](https://docs.datastax.com/en/developer/python-driver/latest/api/cassandra/cluster/#module-cassandra.cluster). The details vary (e.g. with network settings and authentication), but this might be something like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e4b898a5-fe0e-4f11-a87b-7979652322a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from cassandra.cluster import Cluster\n",
    "\n",
    "cluster = Cluster([\"127.0.0.1\"])\n",
    "session = cluster.connect()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6435198e-8713-4045-906b-879613bf5083",
   "metadata": {},
   "source": [
    "You can now set the session, along with your desired keyspace name, as a global CassIO parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "992267dc-0d19-45e0-9a13-ccbb6348d804",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CASSANDRA_KEYSPACE =  demo_keyspace\n"
     ]
    }
   ],
   "source": [
    "import cassio\n",
    "\n",
    "CASSANDRA_KEYSPACE = input(\"CASSANDRA_KEYSPACE = \")\n",
    "\n",
    "cassio.init(session=session, keyspace=CASSANDRA_KEYSPACE)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2cc7ba29-8f84-4fbf-aaf7-3daa1be7e7b0",
   "metadata": {},
   "source": [
    "#### Connecting to Astra DB through CQL\n",
    "\n",
    "In this case you initialize CassIO with the following connection parameters:\n",
    "\n",
    "- the Database ID, e.g. `01234567-89ab-cdef-0123-456789abcdef`\n",
    "- the Token, e.g. `AstraCS:6gBhNmsk135....` (it must be a \"Database Administrator\" token)\n",
    "- Optionally a Keyspace name (if omitted, the default one for the database will be used)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ead97077-cc79-4f5c-940c-91eb21650466",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ASTRA_DB_ID =  01234567-89ab-cdef-0123-456789abcdef\n",
      "ASTRA_DB_APPLICATION_TOKEN =  ········\n",
      "ASTRA_DB_KEYSPACE (optional, can be left empty) =  my_keyspace\n"
     ]
    }
   ],
   "source": [
    "import getpass\n",
    "\n",
    "ASTRA_DB_ID = input(\"ASTRA_DB_ID = \")\n",
    "ASTRA_DB_APPLICATION_TOKEN = getpass.getpass(\"ASTRA_DB_APPLICATION_TOKEN = \")\n",
    "\n",
    "desired_keyspace = input(\"ASTRA_DB_KEYSPACE (optional, can be left empty) = \")\n",
    "if desired_keyspace:\n",
    "    ASTRA_DB_KEYSPACE = desired_keyspace\n",
    "else:\n",
    "    ASTRA_DB_KEYSPACE = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "cc53ce1b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cassio\n",
    "\n",
    "cassio.init(\n",
    "    database_id=ASTRA_DB_ID,\n",
    "    token=ASTRA_DB_APPLICATION_TOKEN,\n",
    "    keyspace=ASTRA_DB_KEYSPACE,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8665664a",
   "metadata": {},
   "source": [
    "### Cassandra: Exact cache\n",
    "\n",
    "This will avoid invoking the LLM when the supplied prompt is _exactly_ the same as one encountered already:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "00a5e66f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.cache import CassandraCache\n",
    "from langchain_core.globals import set_llm_cache\n",
    "\n",
    "set_llm_cache(CassandraCache())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "956a5145",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon is tidally locked with the Earth, which means that its rotation on its own axis is synchronized with its orbit around the Earth. This results in the Moon always showing the same side to the Earth. This is because the gravitational forces between the Earth and the Moon have caused the Moon's rotation to slow down over time, until it reached a point where it takes the same amount of time for the Moon to rotate on its axis as it does to orbit around the Earth. This phenomenon is common among satellites in close orbits around their parent planets and is known as tidal locking.\n",
      "CPU times: user 92.5 ms, sys: 8.89 ms, total: 101 ms\n",
      "Wall time: 1.98 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Why is the Moon always showing the same side?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "158f0151",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon is tidally locked with the Earth, which means that its rotation on its own axis is synchronized with its orbit around the Earth. This results in the Moon always showing the same side to the Earth. This is because the gravitational forces between the Earth and the Moon have caused the Moon's rotation to slow down over time, until it reached a point where it takes the same amount of time for the Moon to rotate on its axis as it does to orbit around the Earth. This phenomenon is common among satellites in close orbits around their parent planets and is known as tidal locking.\n",
      "CPU times: user 5.51 ms, sys: 0 ns, total: 5.51 ms\n",
      "Wall time: 5.78 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Why is the Moon always showing the same side?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fc4d017",
   "metadata": {},
   "source": [
    "### Cassandra: Semantic cache\n",
    "\n",
    "This cache will do a semantic similarity search and return a hit if it finds a cached entry that is similar enough, For this, you need to provide an `Embeddings` instance of your choice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b9ad3f54",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "embedding = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "4623f95e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.cache import CassandraSemanticCache\n",
    "from langchain_core.globals import set_llm_cache\n",
    "\n",
    "set_llm_cache(\n",
    "    CassandraSemanticCache(\n",
    "        embedding=embedding,\n",
    "        table_name=\"my_semantic_cache\",\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1a8e577b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon is always showing the same side because of a phenomenon called synchronous rotation. This means that the Moon rotates on its axis at the same rate that it orbits around the Earth, which takes approximately 27.3 days. This results in the same side of the Moon always facing the Earth. This is due to the gravitational forces between the Earth and the Moon, which have caused the Moon's rotation to gradually slow down and become synchronized with its orbit. This is a common occurrence among many moons in our solar system.\n",
      "CPU times: user 49.5 ms, sys: 7.38 ms, total: 56.9 ms\n",
      "Wall time: 2.55 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Why is the Moon always showing the same side?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "f7abddfd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon is always showing the same side because of a phenomenon called synchronous rotation. This means that the Moon rotates on its axis at the same rate that it orbits around the Earth, which takes approximately 27.3 days. This results in the same side of the Moon always facing the Earth. This is due to the gravitational forces between the Earth and the Moon, which have caused the Moon's rotation to gradually slow down and become synchronized with its orbit. This is a common occurrence among many moons in our solar system.\n",
      "CPU times: user 21.2 ms, sys: 3.38 ms, total: 24.6 ms\n",
      "Wall time: 532 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"How come we always see one face of the moon?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55dc84b3-37cb-4f19-b175-40e18e06f83f",
   "metadata": {},
   "source": [
    "#### Attribution statement\n",
    "\n",
    ">Apache Cassandra, Cassandra and Apache are either registered trademarks or trademarks of the [Apache Software Foundation](http://www.apache.org/) in the United States and/or other countries."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8712f8fc-bb89-4164-beb9-c672778bbd91",
   "metadata": {},
   "source": [
    "## `Astra DB` Caches"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "173041d9-e4af-4f68-8461-d302bfc7e1bd",
   "metadata": {},
   "source": [
    "You can easily use [Astra DB](https://docs.datastax.com/en/astra/home/astra.html) as an LLM cache, with either the \"exact\" or the \"semantic-based\" cache.\n",
    "\n",
    "Make sure you have a running database (it must be a Vector-enabled database to use the Semantic cache) and get the required credentials on your Astra dashboard:\n",
    "\n",
    "- the API Endpoint looks like `https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com`\n",
    "- the Token looks like `AstraCS:6gBhNmsk135....`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "feb510b6-99a3-4228-8e11-563051f8178e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ASTRA_DB_API_ENDPOINT =  https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com\n",
      "ASTRA_DB_APPLICATION_TOKEN =  ········\n"
     ]
    }
   ],
   "source": [
    "import getpass\n",
    "\n",
    "ASTRA_DB_API_ENDPOINT = input(\"ASTRA_DB_API_ENDPOINT = \")\n",
    "ASTRA_DB_APPLICATION_TOKEN = getpass.getpass(\"ASTRA_DB_APPLICATION_TOKEN = \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee6d587f-4b7c-43f4-9e90-5129c842a143",
   "metadata": {},
   "source": [
    "### Astra DB exact LLM cache\n",
    "\n",
    "This will avoid invoking the LLM when the supplied prompt is _exactly_ the same as one encountered already:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ad63c146-ee41-4896-90ee-29fcc39f0ed5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.globals import set_llm_cache\n",
    "from langchain_astradb import AstraDBCache\n",
    "\n",
    "set_llm_cache(\n",
    "    AstraDBCache(\n",
    "        api_endpoint=ASTRA_DB_API_ENDPOINT,\n",
    "        token=ASTRA_DB_APPLICATION_TOKEN,\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "83e0fb02-e8eb-4483-9eb1-55b5e14c4487",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question as it depends on the interpretation of the terms \"true fakery\" and \"fake truth\". However, one possible interpretation is that a true fakery is a counterfeit or imitation that is intended to deceive, whereas a fake truth is a false statement that is presented as if it were true.\n",
      "CPU times: user 70.8 ms, sys: 4.13 ms, total: 74.9 ms\n",
      "Wall time: 2.06 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Is a true fakery the same as a fake truth?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "4d20d498-fe28-4e26-8531-2b31c52ee687",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question as it depends on the interpretation of the terms \"true fakery\" and \"fake truth\". However, one possible interpretation is that a true fakery is a counterfeit or imitation that is intended to deceive, whereas a fake truth is a false statement that is presented as if it were true.\n",
      "CPU times: user 15.1 ms, sys: 3.7 ms, total: 18.8 ms\n",
      "Wall time: 531 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Is a true fakery the same as a fake truth?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "524b94fa-6162-4880-884d-d008749d14e2",
   "metadata": {},
   "source": [
    "### Astra DB Semantic cache\n",
    "\n",
    "This cache will do a semantic similarity search and return a hit if it finds a cached entry that is similar enough, For this, you need to provide an `Embeddings` instance of your choice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "dc329c55-1cc4-4b74-94f9-61f8990fb214",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "embedding = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "83952a90-ab14-4e59-87c0-d2bdc1d43e43",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_astradb import AstraDBSemanticCache\n",
    "\n",
    "set_llm_cache(\n",
    "    AstraDBSemanticCache(\n",
    "        api_endpoint=ASTRA_DB_API_ENDPOINT,\n",
    "        token=ASTRA_DB_APPLICATION_TOKEN,\n",
    "        embedding=embedding,\n",
    "        collection_name=\"demo_semantic_cache\",\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d74b249a-94d5-42d0-af74-f7565a994dea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question since it presupposes a great deal about the nature of truth itself, which is a matter of considerable philosophical debate. It is possible, however, to construct scenarios in which something could be considered true despite being false, such as if someone sincerely believes something to be true even though it is not.\n",
      "CPU times: user 65.6 ms, sys: 15.3 ms, total: 80.9 ms\n",
      "Wall time: 2.72 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Are there truths that are false?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "11973d73-d2f4-46bd-b229-1c589df9b788",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question since it presupposes a great deal about the nature of truth itself, which is a matter of considerable philosophical debate. It is possible, however, to construct scenarios in which something could be considered true despite being false, such as if someone sincerely believes something to be true even though it is not.\n",
      "CPU times: user 29.3 ms, sys: 6.21 ms, total: 35.5 ms\n",
      "Wall time: 1.03 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm.invoke(\"Is is possible that something false can be also true?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40624c26e86b57a4",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Azure Cosmos DB Semantic Cache\n",
    "\n",
    "You can use this integrated [vector database](https://learn.microsoft.com/en-us/azure/cosmos-db/vector-database) for caching."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4a9d592db01b11b2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-18T01:01:32.014750Z",
     "start_time": "2024-03-18T01:01:31.955991Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain_community.cache import AzureCosmosDBSemanticCache\n",
    "from langchain_community.vectorstores.azure_cosmos_db import (\n",
    "    CosmosDBSimilarityType,\n",
    "    CosmosDBVectorSearchType,\n",
    ")\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "# Read more about Azure CosmosDB Mongo vCore vector search here https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/vcore/vector-search\n",
    "\n",
    "NAMESPACE = \"langchain_test_db.langchain_test_collection\"\n",
    "CONNECTION_STRING = (\n",
    "    \"Please provide your azure cosmos mongo vCore vector db connection string\"\n",
    ")\n",
    "\n",
    "DB_NAME, COLLECTION_NAME = NAMESPACE.split(\".\")\n",
    "\n",
    "# Default value for these params\n",
    "num_lists = 3\n",
    "dimensions = 1536\n",
    "similarity_algorithm = CosmosDBSimilarityType.COS\n",
    "kind = CosmosDBVectorSearchType.VECTOR_IVF\n",
    "m = 16\n",
    "ef_construction = 64\n",
    "ef_search = 40\n",
    "score_threshold = 0.9\n",
    "application_name = \"LANGCHAIN_CACHING_PYTHON\"\n",
    "\n",
    "\n",
    "set_llm_cache(\n",
    "    AzureCosmosDBSemanticCache(\n",
    "        cosmosdb_connection_string=CONNECTION_STRING,\n",
    "        cosmosdb_client=None,\n",
    "        embedding=OpenAIEmbeddings(),\n",
    "        database_name=DB_NAME,\n",
    "        collection_name=COLLECTION_NAME,\n",
    "        num_lists=num_lists,\n",
    "        similarity=similarity_algorithm,\n",
    "        kind=kind,\n",
    "        dimensions=dimensions,\n",
    "        m=m,\n",
    "        ef_construction=ef_construction,\n",
    "        ef_search=ef_search,\n",
    "        score_threshold=score_threshold,\n",
    "        application_name=application_name,\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "14ca942820e8140c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-12T00:12:57.462226Z",
     "start_time": "2024-03-12T00:12:55.166201Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 45.6 ms, sys: 19.7 ms, total: 65.3 ms\n",
      "Wall time: 2.29 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy was the math book sad? Because it had too many problems.'"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "bc1570a2a77b58c8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-12T00:13:03.652755Z",
     "start_time": "2024-03-12T00:13:03.159428Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 9.61 ms, sys: 3.42 ms, total: 13 ms\n",
      "Wall time: 474 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy was the math book sad? Because it had too many problems.'"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "306ff47b",
   "metadata": {},
   "source": [
    "## `Elasticsearch` Cache\n",
    "A caching layer for LLMs that uses Elasticsearch.\n",
    "\n",
    "First install the LangChain integration with Elasticsearch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ee5cd3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -U langchain-elasticsearch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e70b0a0",
   "metadata": {},
   "source": [
    "Use the class `ElasticsearchCache`.\n",
    "\n",
    "Simple example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1762c9c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.globals import set_llm_cache\n",
    "from langchain_elasticsearch import ElasticsearchCache\n",
    "\n",
    "set_llm_cache(\n",
    "    ElasticsearchCache(\n",
    "        es_url=\"http://localhost:9200\",\n",
    "        index_name=\"llm-chat-cache\",\n",
    "        metadata={\"project\": \"my_chatgpt_project\"},\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4fac5d6",
   "metadata": {},
   "source": [
    "The `index_name` parameter can also accept aliases. This allows to use the \n",
    "[ILM: Manage the index lifecycle](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html)\n",
    "that we suggest to consider for managing retention and controlling cache growth.\n",
    "\n",
    "Look at the class docstring for all parameters."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eaf9dfd7",
   "metadata": {},
   "source": [
    "### Index the generated text\n",
    "\n",
    "The cached data won't be searchable by default.\n",
    "The developer can customize the building of the Elasticsearch document in order to add indexed text fields,\n",
    "where to put, for example, the text generated by the LLM.\n",
    "\n",
    "This can be done by subclassing end overriding methods.\n",
    "The new cache class can be applied also to a pre-existing cache index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5104c2c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from typing import Any, Dict, List\n",
    "\n",
    "from langchain.globals import set_llm_cache\n",
    "from langchain_core.caches import RETURN_VAL_TYPE\n",
    "from langchain_elasticsearch import ElasticsearchCache\n",
    "\n",
    "\n",
    "class SearchableElasticsearchCache(ElasticsearchCache):\n",
    "    @property\n",
    "    def mapping(self) -> Dict[str, Any]:\n",
    "        mapping = super().mapping\n",
    "        mapping[\"mappings\"][\"properties\"][\"parsed_llm_output\"] = {\n",
    "            \"type\": \"text\",\n",
    "            \"analyzer\": \"english\",\n",
    "        }\n",
    "        return mapping\n",
    "\n",
    "    def build_document(\n",
    "        self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE\n",
    "    ) -> Dict[str, Any]:\n",
    "        body = super().build_document(prompt, llm_string, return_val)\n",
    "        body[\"parsed_llm_output\"] = self._parse_output(body[\"llm_output\"])\n",
    "        return body\n",
    "\n",
    "    @staticmethod\n",
    "    def _parse_output(data: List[str]) -> List[str]:\n",
    "        return [\n",
    "            json.loads(output)[\"kwargs\"][\"message\"][\"kwargs\"][\"content\"]\n",
    "            for output in data\n",
    "        ]\n",
    "\n",
    "\n",
    "set_llm_cache(\n",
    "    SearchableElasticsearchCache(\n",
    "        es_url=\"http://localhost:9200\", index_name=\"llm-chat-cache\"\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db0dea73",
   "metadata": {},
   "source": [
    "When overriding the mapping and the document building, \n",
    "please only make additive modifications, keeping the base mapping intact."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c69d84d",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Optional Caching\n",
    "You can also turn off caching for specific LLMs should you choose. In the example below, even though global caching is enabled, we turn it off for a specific LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "6af46e2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", n=2, best_of=2, cache=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "26c4fd8f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 5.8 ms, sys: 2.71 ms, total: 8.51 ms\n",
      "Wall time: 745 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "46846b20",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.91 ms, sys: 2.64 ms, total: 7.55 ms\n",
      "Wall time: 623 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nTwo guys stole a calendar. They got six months each.'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5da41b77",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Optional Caching in Chains\n",
    "You can also turn off caching for particular nodes in chains. Note that because of certain interfaces, its often easier to construct the chain first, and then edit the LLM afterwards.\n",
    "\n",
    "As an example, we will load a summarizer map-reduce chain. We will cache results for the map-step, but then not freeze it for the combine step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9afa3f7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\")\n",
    "no_cache_llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", cache=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "98a78e8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_text_splitters import CharacterTextSplitter\n",
    "\n",
    "text_splitter = CharacterTextSplitter()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "2bfb099b",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"../../how_to/state_of_the_union.txt\") as f:\n",
    "    state_of_the_union = f.read()\n",
    "texts = text_splitter.split_text(state_of_the_union)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f78b7f51",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.documents import Document\n",
    "\n",
    "docs = [Document(page_content=t) for t in texts[:3]]\n",
    "from langchain.chains.summarize import load_summarize_chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "a2a30822",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_summarize_chain(llm, chain_type=\"map_reduce\", reduce_llm=no_cache_llm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a545b743",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 452 ms, sys: 60.3 ms, total: 512 ms\n",
      "Wall time: 5.09 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure. In response to Russian aggression in Ukraine, the United States is joining with European allies to impose sanctions and isolate Russia. American forces are being mobilized to protect NATO countries in the event that Putin decides to keep moving west. The Ukrainians are bravely fighting back, but the next few weeks will be hard for them. Putin will pay a high price for his actions in the long run. Americans should not be alarmed, as the United States is taking action to protect its interests and allies.'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "chain.run(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ed85e9d",
   "metadata": {},
   "source": [
    "When we run it again, we see that it runs substantially faster but the final answer is different. This is due to caching at the map steps, but not at the reduce step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "39cbb282",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 11.5 ms, sys: 4.33 ms, total: 15.8 ms\n",
      "Wall time: 1.04 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure.'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "chain.run(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9df0dab8",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm .langchain.db sqlite.db"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "544a90cbdd9894ba",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "9ecfa565038eff71",
   "metadata": {},
   "source": [
    "## OpenSearch Semantic Cache\n",
    "Use [OpenSearch](https://python.langchain.com/docs/integrations/vectorstores/opensearch/) as a semantic cache to cache prompts and responses and evaluate hits based on semantic similarity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7379fd5aa83ee500",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-12T02:06:03.766873Z",
     "start_time": "2024-04-12T02:06:03.754481Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain_community.cache import OpenSearchSemanticCache\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "set_llm_cache(\n",
    "    OpenSearchSemanticCache(\n",
    "        opensearch_url=\"http://localhost:9200\", embedding=OpenAIEmbeddings()\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "fecb26634bf27e93",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-12T02:06:08.734403Z",
     "start_time": "2024-04-12T02:06:07.178381Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 39.4 ms, sys: 11.8 ms, total: 51.2 ms\n",
      "Wall time: 1.55 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\n\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "43b24b725ea4ba98",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-12T02:06:12.073448Z",
     "start_time": "2024-04-12T02:06:11.957571Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.66 ms, sys: 1.1 ms, total: 5.76 ms\n",
      "Wall time: 113 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\n\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time, while not a direct hit, the question is semantically similar to the original question,\n",
    "# so it uses the cached result!\n",
    "llm(\"Tell me one joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ac1a8c7",
   "metadata": {},
   "source": [
    "## SingleStoreDB Semantic Cache\n",
    "You can use [SingleStoreDB](https://python.langchain.com/docs/integrations/vectorstores/singlestoredb/) as a semantic cache to cache prompts and responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d82f1bdc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.cache import SingleStoreDBSemanticCache\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "set_llm_cache(\n",
    "    SingleStoreDBSemanticCache(\n",
    "        embedding=OpenAIEmbeddings(),\n",
    "        host=\"root:pass@localhost:3306/db\",\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7019c991-0101-4f9c-b212-5729a5471293",
   "metadata": {},
   "source": [
    "## Couchbase Caches\n",
    "\n",
    "Use [Couchbase](https://couchbase.com/) as a cache for prompts and responses."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6aac680-ba32-4c19-8864-6471cf0e7d5a",
   "metadata": {},
   "source": [
    "### Couchbase Cache\n",
    "\n",
    "The standard cache that looks for an exact match of the user prompt."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9b4764e4-c75f-4185-b326-524287a826be",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create couchbase connection object\n",
    "from datetime import timedelta\n",
    "\n",
    "from couchbase.auth import PasswordAuthenticator\n",
    "from couchbase.cluster import Cluster\n",
    "from couchbase.options import ClusterOptions\n",
    "from langchain_couchbase.cache import CouchbaseCache\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "COUCHBASE_CONNECTION_STRING = (\n",
    "    \"couchbase://localhost\"  # or \"couchbases://localhost\" if using TLS\n",
    ")\n",
    "DB_USERNAME = \"Administrator\"\n",
    "DB_PASSWORD = \"Password\"\n",
    "\n",
    "auth = PasswordAuthenticator(DB_USERNAME, DB_PASSWORD)\n",
    "options = ClusterOptions(auth)\n",
    "cluster = Cluster(COUCHBASE_CONNECTION_STRING, options)\n",
    "\n",
    "# Wait until the cluster is ready for use.\n",
    "cluster.wait_until_ready(timedelta(seconds=5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4b5e73c5-92c1-4eab-84e2-77924ea9c123",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Specify the bucket, scope and collection to store the cached documents\n",
    "BUCKET_NAME = \"langchain-testing\"\n",
    "SCOPE_NAME = \"_default\"\n",
    "COLLECTION_NAME = \"_default\"\n",
    "\n",
    "set_llm_cache(\n",
    "    CouchbaseCache(\n",
    "        cluster=cluster,\n",
    "        bucket_name=BUCKET_NAME,\n",
    "        scope_name=SCOPE_NAME,\n",
    "        collection_name=COLLECTION_NAME,\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "db8d28cc-8d93-47b4-8326-57a29a06fb3c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 22.2 ms, sys: 14 ms, total: 36.2 ms\n",
      "Wall time: 938 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy couldn't the bicycle stand up by itself? Because it was two-tired!\""
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in the cache, so it should take longer\n",
    "llm.invoke(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b470dc81-2e7f-4743-9435-ce9071394eea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 53 ms, sys: 29 ms, total: 82 ms\n",
      "Wall time: 84.2 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy couldn't the bicycle stand up by itself? Because it was two-tired!\""
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time, it is in the cache, so it should be much faster\n",
    "llm.invoke(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43626f33-d184-4260-b641-c9341cef5842",
   "metadata": {},
   "source": [
    "### Couchbase Semantic Cache\n",
    "Semantic caching allows users to retrieve cached prompts based on semantic similarity between the user input and previously cached inputs. Under the hood it uses Couchbase as both a cache and a vectorstore. This needs an appropriate Vector Search Index defined to work. Please look at the usage example on how to set up the index."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6b470c03-d7fe-4270-89e1-638251619a53",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Couchbase connection object\n",
    "from datetime import timedelta\n",
    "\n",
    "from couchbase.auth import PasswordAuthenticator\n",
    "from couchbase.cluster import Cluster\n",
    "from couchbase.options import ClusterOptions\n",
    "from langchain_couchbase.cache import CouchbaseSemanticCache\n",
    "from langchain_openai import ChatOpenAI, OpenAIEmbeddings\n",
    "\n",
    "COUCHBASE_CONNECTION_STRING = (\n",
    "    \"couchbase://localhost\"  # or \"couchbases://localhost\" if using TLS\n",
    ")\n",
    "DB_USERNAME = \"Administrator\"\n",
    "DB_PASSWORD = \"Password\"\n",
    "\n",
    "auth = PasswordAuthenticator(DB_USERNAME, DB_PASSWORD)\n",
    "options = ClusterOptions(auth)\n",
    "cluster = Cluster(COUCHBASE_CONNECTION_STRING, options)\n",
    "\n",
    "# Wait until the cluster is ready for use.\n",
    "cluster.wait_until_ready(timedelta(seconds=5))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f831bc4c-f330-4bd7-9b80-76771d91827e",
   "metadata": {},
   "source": [
    "Notes:\n",
    "- The search index for the semantic cache needs to be defined before using the semantic cache. \n",
    "- The optional parameter, `score_threshold` in the Semantic Cache that you can use to tune the results of the semantic search.\n",
    "\n",
    "### How to Import an Index to the Full Text Search service?\n",
    " - [Couchbase Server](https://docs.couchbase.com/server/current/search/import-search-index.html)\n",
    "     - Click on Search -> Add Index -> Import\n",
    "     - Copy the following Index definition in the Import screen\n",
    "     - Click on Create Index to create the index.\n",
    " - [Couchbase Capella](https://docs.couchbase.com/cloud/search/import-search-index.html)\n",
    "     - Copy the index definition to a new file `index.json`\n",
    "     - Import the file in Capella using the instructions in the documentation.\n",
    "     - Click on Create Index to create the index.\n",
    "\n",
    "#### Example index for the vector search. \n",
    "  ```\n",
    "  {\n",
    "    \"type\": \"fulltext-index\",\n",
    "    \"name\": \"langchain-testing._default.semantic-cache-index\",\n",
    "    \"sourceType\": \"gocbcore\",\n",
    "    \"sourceName\": \"langchain-testing\",\n",
    "    \"planParams\": {\n",
    "      \"maxPartitionsPerPIndex\": 1024,\n",
    "      \"indexPartitions\": 16\n",
    "    },\n",
    "    \"params\": {\n",
    "      \"doc_config\": {\n",
    "        \"docid_prefix_delim\": \"\",\n",
    "        \"docid_regexp\": \"\",\n",
    "        \"mode\": \"scope.collection.type_field\",\n",
    "        \"type_field\": \"type\"\n",
    "      },\n",
    "      \"mapping\": {\n",
    "        \"analysis\": {},\n",
    "        \"default_analyzer\": \"standard\",\n",
    "        \"default_datetime_parser\": \"dateTimeOptional\",\n",
    "        \"default_field\": \"_all\",\n",
    "        \"default_mapping\": {\n",
    "          \"dynamic\": true,\n",
    "          \"enabled\": false\n",
    "        },\n",
    "        \"default_type\": \"_default\",\n",
    "        \"docvalues_dynamic\": false,\n",
    "        \"index_dynamic\": true,\n",
    "        \"store_dynamic\": true,\n",
    "        \"type_field\": \"_type\",\n",
    "        \"types\": {\n",
    "          \"_default.semantic-cache\": {\n",
    "            \"dynamic\": false,\n",
    "            \"enabled\": true,\n",
    "            \"properties\": {\n",
    "              \"embedding\": {\n",
    "                \"dynamic\": false,\n",
    "                \"enabled\": true,\n",
    "                \"fields\": [\n",
    "                  {\n",
    "                    \"dims\": 1536,\n",
    "                    \"index\": true,\n",
    "                    \"name\": \"embedding\",\n",
    "                    \"similarity\": \"dot_product\",\n",
    "                    \"type\": \"vector\",\n",
    "                    \"vector_index_optimized_for\": \"recall\"\n",
    "                  }\n",
    "                ]\n",
    "              },\n",
    "              \"metadata\": {\n",
    "                \"dynamic\": true,\n",
    "                \"enabled\": true\n",
    "              },\n",
    "              \"text\": {\n",
    "                \"dynamic\": false,\n",
    "                \"enabled\": true,\n",
    "                \"fields\": [\n",
    "                  {\n",
    "                    \"index\": true,\n",
    "                    \"name\": \"text\",\n",
    "                    \"store\": true,\n",
    "                    \"type\": \"text\"\n",
    "                  }\n",
    "                ]\n",
    "              }\n",
    "            }\n",
    "          }\n",
    "        }\n",
    "      },\n",
    "      \"store\": {\n",
    "        \"indexType\": \"scorch\",\n",
    "        \"segmentVersion\": 16\n",
    "      }\n",
    "    },\n",
    "    \"sourceParams\": {}\n",
    "  }\n",
    "  ```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ae0766c8-ea34-4604-b0dc-cf2bbe8077f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "BUCKET_NAME = \"langchain-testing\"\n",
    "SCOPE_NAME = \"_default\"\n",
    "COLLECTION_NAME = \"semantic-cache\"\n",
    "INDEX_NAME = \"semantic-cache-index\"\n",
    "embeddings = OpenAIEmbeddings()\n",
    "\n",
    "cache = CouchbaseSemanticCache(\n",
    "    cluster=cluster,\n",
    "    embedding=embeddings,\n",
    "    bucket_name=BUCKET_NAME,\n",
    "    scope_name=SCOPE_NAME,\n",
    "    collection_name=COLLECTION_NAME,\n",
    "    index_name=INDEX_NAME,\n",
    "    score_threshold=0.8,\n",
    ")\n",
    "\n",
    "set_llm_cache(cache)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a2e82743-10ea-4319-b43e-193475ae5449",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The average lifespan of a dog is around 12 years, but this can vary depending on the breed, size, and overall health of the individual dog. Some smaller breeds may live longer, while larger breeds may have shorter lifespans. Proper care, diet, and exercise can also play a role in extending a dog's lifespan.\n",
      "CPU times: user 826 ms, sys: 2.46 s, total: 3.28 s\n",
      "Wall time: 2.87 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in the cache, so it should take longer\n",
    "print(llm.invoke(\"How long do dogs live?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c36f4e29-d872-4334-a1f1-0e6d10c5d9f2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The average lifespan of a dog is around 12 years, but this can vary depending on the breed, size, and overall health of the individual dog. Some smaller breeds may live longer, while larger breeds may have shorter lifespans. Proper care, diet, and exercise can also play a role in extending a dog's lifespan.\n",
      "CPU times: user 9.82 ms, sys: 2.61 ms, total: 12.4 ms\n",
      "Wall time: 311 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# The second time, it is in the cache, so it should be much faster\n",
    "print(llm.invoke(\"What is the expected lifespan of a dog?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae1f5e1c-085e-4998-9f2d-b5867d2c3d5b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-31T17:18:43.345495Z",
     "iopub.status.busy": "2024-05-31T17:18:43.345015Z",
     "iopub.status.idle": "2024-05-31T17:18:43.351003Z",
     "shell.execute_reply": "2024-05-31T17:18:43.350073Z",
     "shell.execute_reply.started": "2024-05-31T17:18:43.345456Z"
    }
   },
   "source": [
    "## Cache classes: summary table"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65072e45-10bc-40f1-979b-2617656bbbce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-31T17:16:05.616430Z",
     "iopub.status.busy": "2024-05-31T17:16:05.616221Z",
     "iopub.status.idle": "2024-05-31T17:16:05.624164Z",
     "shell.execute_reply": "2024-05-31T17:16:05.623673Z",
     "shell.execute_reply.started": "2024-05-31T17:16:05.616418Z"
    }
   },
   "source": [
    "**Cache** classes are implemented by inheriting the [BaseCache](https://api.python.langchain.com/en/latest/caches/langchain_core.caches.BaseCache.html) class.\n",
    "\n",
    "This table lists all 21 derived classes with links to the API Reference.\n",
    "\n",
    "\n",
    "| Namespace 🔻 | Class |\n",
    "|------------|---------|\n",
    "| langchain_astradb.cache | [AstraDBCache](https://api.python.langchain.com/en/latest/cache/langchain_astradb.cache.AstraDBCache.html) |\n",
    "| langchain_astradb.cache | [AstraDBSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_astradb.cache.AstraDBSemanticCache.html) |\n",
    "| langchain_community.cache | [AstraDBCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.AstraDBCache.html) |\n",
    "| langchain_community.cache | [AstraDBSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.AstraDBSemanticCache.html) |\n",
    "| langchain_community.cache | [AzureCosmosDBSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.AzureCosmosDBSemanticCache.html) |\n",
    "| langchain_community.cache | [CassandraCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.CassandraCache.html) |\n",
    "| langchain_community.cache | [CassandraSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.CassandraSemanticCache.html) |\n",
    "| langchain_community.cache | [GPTCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.GPTCache.html) |\n",
    "| langchain_community.cache | [InMemoryCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.InMemoryCache.html) |\n",
    "| langchain_community.cache | [MomentoCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.MomentoCache.html) |\n",
    "| langchain_community.cache | [OpenSearchSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.OpenSearchSemanticCache.html) |\n",
    "| langchain_community.cache | [RedisSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.RedisSemanticCache.html) |\n",
    "| langchain_community.cache | [SingleStoreDBSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.SingleStoreDBSemanticCache.html) |\n",
    "| langchain_community.cache | [SQLAlchemyCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.SQLAlchemyCache.html) |\n",
    "| langchain_community.cache | [SQLAlchemyMd5Cache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.SQLAlchemyMd5Cache.html) |\n",
    "| langchain_community.cache | [UpstashRedisCache](https://api.python.langchain.com/en/latest/cache/langchain_community.cache.UpstashRedisCache.html) |\n",
    "| langchain_core.caches | [InMemoryCache](https://api.python.langchain.com/en/latest/caches/langchain_core.caches.InMemoryCache.html) |\n",
    "| langchain_elasticsearch.cache | [ElasticsearchCache](https://api.python.langchain.com/en/latest/cache/langchain_elasticsearch.cache.ElasticsearchCache.html) |\n",
    "| langchain_mongodb.cache | [MongoDBAtlasSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_mongodb.cache.MongoDBAtlasSemanticCache.html) |\n",
    "| langchain_mongodb.cache | [MongoDBCache](https://api.python.langchain.com/en/latest/cache/langchain_mongodb.cache.MongoDBCache.html) |\n",
    "| langchain_couchbase.cache | [CouchbaseCache](https://api.python.langchain.com/en/latest/cache/langchain_couchbase.cache.CouchbaseCache.html) |\n",
    "| langchain_couchbase.cache | [CouchbaseSemanticCache](https://api.python.langchain.com/en/latest/cache/langchain_couchbase.cache.CouchbaseSemanticCache.html) |\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19067f14-c69a-4156-9504-af43a0713669",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
